package cn.xiaopengstack.domain.award.service.distribute.impl;

import cn.xiaopengstack.domain.award.aggregate.GiveOutCreditAwardAggregate;
import cn.xiaopengstack.domain.award.model.entity.DistributeMatterEntity;
import cn.xiaopengstack.domain.award.model.entity.UserCreditAwardEntity;
import cn.xiaopengstack.domain.award.repository.IRaffleAwardRepository;
import cn.xiaopengstack.domain.award.service.distribute.IDistributeAward;
import cn.xiaopengstack.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * @author jiangyangang
 * 随机积分奖励实现
 */
@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {

    @Resource
    private IRaffleAwardRepository raffleAwardRepository;

    @Override
    public void distribute(DistributeMatterEntity distributeMatter) {

        // 额度拆分
        String awardConfig = distributeMatter.getAwardEntity().getAwardConfig();
        String[] splitConfig = awardConfig.split(Constants.SPLIT);
        BigDecimal min = new BigDecimal(splitConfig[0]);
        BigDecimal max = new BigDecimal(splitConfig[1]);

        BigDecimal creditAmount;
        if (min.equals(max)) {
            creditAmount = min;
        } else {
            BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
            creditAmount = randomBigDecimal.round(new MathContext(3));
        }

        GiveOutCreditAwardAggregate giveOutCreditAwardAggregate = new GiveOutCreditAwardAggregate();
        giveOutCreditAwardAggregate.setUserId(distributeMatter.getUserId());
        giveOutCreditAwardAggregate.setUserAwardRecordEntity(distributeMatter.getUserAwardRecordEntity());
        giveOutCreditAwardAggregate.setUserCreditAwardEntity(UserCreditAwardEntity.builder()
                .creditAmount(creditAmount)
                .userId(distributeMatter.getUserId())
                .build());
        raffleAwardRepository.saveGiveOutCreditAwardOrder(giveOutCreditAwardAggregate);
    }
}
